#!/usr/bin/env perl

# Sentinel - IRC Statistical and Operator Services
# installpatch.pl - Sentinel patch application script
#
# Copyright W. Campbell and others.  See README for more details
# Some code Copyright: Jonathan George, Kai Seidler, ircd-hybrid Team,
#                      IRCnet IRCD developers.
#
# $Id: installpatch.pl.in 7 2010-02-01 19:17:42Z dubkat $

$basepath = '@SOURCE_ROOT@';

# First, test if the file is valid
$patch = shift or die "$0:  syntax: $0 <patchfile>\n";

# Second, extract the patch name from the patch file
$patchname = "";
$notenum = 0;
open(PATCH, "<$patch") or die "$0:  unable to open patch file $patch\n";
while ($patchline = <PATCH>)
{
  chomp;
  if ($patchline =~ /\$PATCH: (.*)/)
  {
    $patchname = $1;
  }
  elsif ($patchline =~ /\$NOTE: (.*)/)
  {
    $notes[$notenum] = $1;
    $notenum++;
  }
  else
  {
    break;
  }
}

if ($patchname eq "")
{
  print "WARNING:  No patch name in patch.\n";
}
close(PATCH);

# Third, apply the patch
if ($basepath ne '@SOURCE_ROOT@')
{
  chdir($basepath);
}
# else, assume the best
system("patch < $patch");

# Last, set the patches variable in src/geninfo.sh script
system("cp src/geninfo.sh src/geninfo.sh.patch");
open(ININFO, "<src/geninfo.sh.patch"); # or die?
open(OUTINFO, ">src/geninfo.sh");
while (<ININFO>)
{
  if (/patches\=\"(.*)\"/)
  {
    print OUTINFO "patches=\"${1}${patchname}\"\n";
  }
  else
  {
    print OUTINFO $_;
  }
}
close(ININFO);
close(OUTINFO);

# And we're finished
print "Patch $patchname ($patch) applied.\n\n";
if ($notenum > 0)
{
  for ($i = 0; $i < $notenum; $i++)
  {
    print "NOTE: $notes[$i]\n";
  }
}

exit 0;

